﻿var express = require('express');
var router = express.Router();



router.get('/login', function (req, res, next) {
    res.cookie('token', "");   
    res.render('admin/login', { title: 'Express' });        
});


router.get('/',verifyToken, function (req, res, next) {
    res.render('admin/index', { title: 'Express' });
});
router.get('/index',verifyToken, function (req, res, next) {  
   res.render('admin/index', { title: 'Express' });
});

router.get('/product',verifyToken, function (req, res, next) {
   res.render('admin/product', { title: 'Express' });
});

router.get('/news',verifyToken, function (req, res, next) {
   res.render('admin/news', { title: 'Express' });
});

router.get('/navitem',verifyToken, function (req, res, next) {
    res.render('admin/navitem', { title: 'Express' });
});
router.get('/leaveMessages',verifyToken, function (req, res, next) {
    res.render('admin/leaveMessages', { title: 'Express' }); 
});

router.get('/registUserList',verifyToken, function (req, res, next) {
    res.render('admin/registUserList', { title: 'Express' });
});

//在项目目录中，通过npm install connect-multiparty进行安装必要组件。
//在项目目录中，通过npm install multiparty进行安装必要组件。
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');

router.post('/upload', function (req, res, next) {
   try{
    var form = new multiparty.Form({ uploadDir: './public/files/upload/' });
    form.parse(req, function (err, fields, files) {
        var respage = "";
        var filesTmp = JSON.stringify(files,null,2);              
        if(err){
            //respage = operateUpload(req,"error",err);
			res.send(false);
            } else {
			  for(i=0;i<files.inputFile.length;i++){
				    var inputFile = files.inputFile[i];
					var uploadedPath = inputFile.path;
					var cDate = new Date();
					var date = cDate.getFullYear().toString() + "-" + (cDate.getMonth() + 1).toString() + "-" + cDate.getDate().toString()
					+ (cDate.getHours()+1).toString()
					+ cDate.getMinutes().toString()
					+ cDate.getSeconds().toString()
					+ cDate.getMilliseconds().toString();

					var filename = req.query.type +"("+ date+")_" + inputFile.originalFilename;
					var dstPath = './public/files/upload/' + filename;
					renameMyFile(req,filename,uploadedPath,dstPath);
					}
					 res.json(true);
			  }
            
           
       });
   }
   catch(ex){
    console.log("catch:"+ex.message)
    // respage = operateUpload(req,"error","");
    // res.end(respage);
	res.send(false);
   }

   
});

function renameMyFile(req,filename,uploadedPath,dstPath){
	//重命名为真实文件名
	fs.rename(uploadedPath, dstPath, function(err) {
			if(err){
				console.log('rename error: ' + err);
				res.send(false);
				} else {
				//保存业务数据
				ResizeImg(filename);
				operateUpload(req, "true", filename);				
				}
		});
}


//需要安装 npm install images
function ResizeImg(filename) {
   var images = require("images");    
	images('./public/files/upload/' + filename)                                        
	.resize(400) 
	.save('./public/files/upload/small/' + filename, {
	});
	
	
	images('./public/files/upload/' + filename)                                        
	.resize(200) 
	.save('./public/files/upload/xsmall/' + filename, {
	});
}

function operateUpload(req, flag,filename) {
    var type = req.query.type;
    var parames = "type="+type;

    if (flag == "true") {
        var date = new Date();

        var imageObj = {};
        if (type == "rollimageAdd") {            
            imageObj.filename = filename;
            imageObj.order = "0";
            imageObj.createDate = date;
            saveRollImage(imageObj);
        }
        else if (type == "navimageAdd") {           
            imageObj.filename = filename;           
            imageObj.typeCode = "";
            imageObj.typeName = "";
            imageObj.createDate = date;
            savenavImage(imageObj);
        }
        else if (type == "productAdd") {
            var images = require("images");
            var sourceImg = images('./public/files/upload/' + filename);          
            var sWidth = sourceImg.width();
            var sHeight = sourceImg.height();
            imageObj.width=sWidth;
            imageObj.height=sHeight;
            imageObj.filename = filename;            
            imageObj.createDate = date;
            saveproduct(imageObj);
        }
        else if (type == "childrenImgAdd") {
            var images = require("images");
            var sourceImg = images('./public/files/upload/' + filename);
            var sWidth = sourceImg.width();
            var sHeight = sourceImg.height();

            parames += "&parentId=" + req.query.parentId;
            console.log(parames);
            imageObj.parentId= req.query.parentId;
            imageObj.filename = filename;
            imageObj.width=sWidth;
            imageObj.height=sHeight;
            savechildrenImgAdd(imageObj);
        }
        else if(type=="newsImageAdd"){
            imageObj.filename = filename;            
            imageObj.createDate = date;
            savenewsImage(imageObj);
        }       
    } 
}
//首页图片管理
var rollImage = require('../../app_modules/dbAccess/rollImage_Mongo.js');
function saveRollImage(obj) {
    try{
        console.log("rollimage--add");
    var rollImageObj = new rollImage();
    rollImageObj.add({
        title:"",
        description:"",
        takeDate:"",
        filename: obj.filename,
        createDate: obj.createDate,
        order: obj.order
    }, function (err, rs) {
        if (err) {
            console.log(err);
            console.log("save failed");
            //res.json({ success: false });
        } else {
            //res.json({ success: true });
            console.log("save ok");
        }

    });
}catch(ex){
    console.log("save failed");
}
    
}
router.post('/getrollImages', function (req, res) {
    try{
        console.log("getrollImages");
    var rollImages = rollImage.find().sort({ createDate: -1 }).exec(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            //console.log("加载完毕：" + (new Date).toLocaleTimeString());
            res.json(result);
        }
    });
}catch(ex){
    res.send("");
}
    
});


router.post('/removerollImages', function (req, res) {    
    console.log("removerollImages");
    var id = req.query._id;
    var fileName = req.query.fileName;
    console.log("_id:"+id);
    rollImage.remove({ _id: id }, function (err, rs) {
        try{
            if (err) {           
            res.json({ success: false });
        }
        else {

            fs.unlinkSync("./public/files/upload/" + fileName);
            fs.unlinkSync("./public/files/upload/small/" + fileName);
            res.json({ success: true });
        }
        }
        catch(ex)
        {
            console.log(ex.message);
            res.json({ success: false });
        }
        
    });
});


var mongoose = require('mongoose');
router.post('/editrollImages', function (req, res) {
   try{
     console.log("editrollImages");
    console.log(req.body.title);

    var id = req.body._id;
    var tempid = mongoose.Types.ObjectId(id);
    rollImage.update({ _id: tempid }, {
        $set: {
            title: req.body.title,
            description: req.body.description,
            takeDate: req.body.takeDate,
            order: req.body.order
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            res.json({ success: true });
        }

    });
   }catch(ex){

   }
});


//模块图片管理
var navImage = require('../../app_modules/dbAccess/navImage_Mongo.js');
function savenavImage(obj) {
    try{
        console.log("navimage--add");
    var navImageObj = new navImage();
    navImageObj.add({
        typeCode: obj.typeCode,
        typeName: obj.typeName,
        filename: obj.filename
    }, function (err, rs) {
        if (err) {
            console.log(err);
            console.log("save failed");
            //res.json({ success: false });
        } else {
            //res.json({ success: true });
            console.log("save ok");
        }

    });
    }catch(ex){

    }
}
router.post('/getnavImages', function (req, res) {
    try{
        console.log("getnavImages");
    var navImages = navImage.find(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            //console.log("加载完毕：" + (new Date).toLocaleTimeString());
            res.json(result);
        }
    });
}catch(ex){
    console.log(ex.message);
            res.send("");
}
});


router.post('/removenavImages', function (req, res) {
    console.log("removenavImages");
    var id = req.query._id;
    var fileName = req.query.fileName;
    console.log("_id:" + id);
    navImage.remove({ _id: id }, function (err, rs) {
        if (err) {
            res.json({ success: false });
        }
        else {
            try{
            fs.unlinkSync("./public/files/upload/" + fileName);
            fs.unlinkSync("./public/files/upload/small/" + fileName);
            res.json({ success: true });
            }
            catch(ex){
                console.log(ex.message);
                res.json({ success: false });
            }
            
        }
    });
});


router.post('/editnavImages', function (req, res) {
    try{
        console.log("editnavImages");
    var id = req.body._id;
    var tempid = mongoose.Types.ObjectId(id);
    navImage.update({ _id: tempid }, {
        $set: {
            typeCode: req.body.navType.id,
            typeName: req.body.navType.name
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            res.json({ success: true });
        }

    });}catch(ex){

    }
});

//作品集封面管理
var product = require('../../app_modules/dbAccess/product_Mongo.js');
function saveproduct(obj) {
    try{
    console.log("saveproduct--add");
    var productObj = new product();
    productObj.add({
        title: "",
        description: "",
        filename: obj.filename,
        createDate: new Date(),
        images: [{filename:obj.filename,description:"",createDate:new Date(),width:obj.width,
        height:obj.height}],
        width:obj.width,
        height:obj.height
    }, function (err, rs) {
        if (err) {
            console.log(err);
            console.log("save failed");
            //res.json({ success: false });
        } else {
            //res.json({ success: true });
            console.log("save ok");
        }

    });    
    }catch(ex){

    }
    
}

router.post('/getproducts', function (req, res) {
   try{
     console.log("getproducts");
     var pageIndex=req.body.pageIndex-1;
     var pageSize=parseInt(req.body.pageSize);
     var products = product.find().sort({ createDate: -1 }).skip(pageIndex*pageSize).limit(pageSize).exec(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            //console.log("加载完毕：" + (new Date).toLocaleTimeString());
			res.header("Access-Control-Allow-Origin", "*");
            res.json(result);
        }
    });}catch(ex){res.send("")}
});

router.post('/removeproduct', function (req, res) {
    console.log("removeproduct");
    var id = req.query._id;
    var fileName = req.query.fileName;
    console.log("_id:" + id);
    product.remove({ _id: id }, function (err, rs) {
        if (err) {
            res.json({ success: false });
        }
        else {
            try{

            fs.unlinkSync("./public/files/upload/" + fileName);
            fs.unlinkSync("./public/files/upload/small/" + fileName);
            res.json({ success: true });
            }
            catch(ex){
                console.log(ex.message);
                res.json({ success: false });
            }
        }
    });
});

router.post('/editproduct', function (req, res) {
    try{
       console.log("editproduct");
    var id = req.body._id;
    var tempid = mongoose.Types.ObjectId(id);
    console.log(tempid);
    product.update({ _id: tempid }, {
        $set: {
            title: req.body.title,
            description: req.body.description
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            res.json({ success: true });
        }

    }); 
}catch(ex){
}
    
});

router.post('/setCover', function (req, res) {
  try{  console.log("setCover");
    var id = req.body._id;
    var tempid = mongoose.Types.ObjectId(id);
    console.log(tempid);
    product.update({ _id: tempid }, {
        $set: {
            filename:req.body.filename
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            res.json({ success: true });
        }

    });}catch(ex){}
});


router.post('/getproduct', function (req, res) {
    try{console.log("getproduct");
    var id = req.body.id;
    var students = product.findOne({ _id: id }, function (err, result) {
        if (err) {
            res.send(err);
        } else {
			res.header("Access-Control-Allow-Origin", "*");
            res.json(result);
        }
    });}catch(ex){}
});

//图片集内照片管理
function savechildrenImgAdd(obj) {    
    try{console.log("savechildrenImgAdd--add");
    var tempid = obj.parentId;
    console.log("tempid:"+tempid);
    product.update({ _id: tempid }, {
        $push: {
            images: {
                filename: obj.filename,
                description: "",
                createDate:new Date(),
                width:obj.width,
                height:obj.height
            }
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            console.log("success");
        }

    });}catch(ex){}
}

function removechildrenImg(obj) {
    try{
        console.log("savechildrenImgAdd--add");
    var tempid = obj.parentId;
    console.log("tempid:" + tempid);
    product.update({ _id: tempid }, {
        $pull: {
            images: {
                _id:obj._id
            }
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            console.log("success");
        }

    });
}catch(ex){
}
    
}


router.post('/childImgEdit', function (req, res) {
    try{
        console.log("childImgEdit");
    var parentid = req.body.parentid;
    var _id = req.body._id;
    var description = req.body.description;
    console.log("parentid:" + parentid);
    console.log("_id:" + _id);
    console.log("description:" + description);

    product.findById(parentid, function (err, rs) {
        if (err) {
            res.json({ success: false });
        }
        else {
            for (var i = 0; i < rs.images.length; i++) {
                if (rs.images[i]._id == _id) {
                    rs.images[i].description = description;
                    rs.markModified('description');
                    //保存
                    rs.save(function (err) {
                        res.json({ status: 1, error: '修改成功！' });
                        return;
                    });
                }
            }
        }       
    })
}catch(ex){}
});


router.post('/removechildrenImg', function (req, res) {
    try{
        console.log("removechildrenImg");
    var parentid = req.body.parentid;
    var filename = req.body.filename;
    console.log("parentid:" + parentid);
    console.log("_id:" + req.body._id);
    console.log("filename:" + filename);

    product.update({ _id: parentid }, {
        $pull: {
            images: {_id: req.body._id}
        }
    }, function (err, rs) {
        if (err) {
            res.json({ success: false });
        }
        else {
             try{

            fs.unlinkSync("./public/files/upload/" + fileName);
            fs.unlinkSync("./public/files/upload/small/" + fileName);
            res.json({ success: true });
            }
            catch(ex){
                console.log(ex.message);
                res.json({ success: false });
            }
        }
    });
}catch(ex){}
});

//留言管理
var message = require('../../app_modules/dbAccess/message_Mongo.js');

router.post('/saveLeavemassage', function (req, res) {
    try{console.log("saveLeavemassage");
    var messageObj = new message();
    messageObj.add({
        name: req.body.name,
        telphone: req.body.telphone,
        email: req.body.email,
        qq: req.body.qq,
        weixin: req.body.weixin,
        leaveMsg: req.body.leaveMsg,
        createDate: new Date(),
        flag:"0",
    }, function (err, rs) {
        if (err) {
            console.log(err);
            res.json({ success: false });
        } else {
            res.json({ success: true });
        }

    });}catch(ex){}
});

router.post('/Getmessages', function (req, res) {
   try{ console.log("Getmessages");
    var messages = message.find(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            //console.log("加载完毕：" + (new Date).toLocaleTimeString());
            res.json(result);
        }
    });}catch(ex){}
});


router.post('/updateMsgFlag', function (req, res) {
    try{console.log("updateMsgFlag");
    var objList = req.body.list;
    for (i = 0; i < objList.length; i++)
    {
        tempid = objList[i]._id;
        console.log(tempid);
        message.update({ _id: tempid }, {
            $set: {
                flag: objList[0].flag
            }
        }, function (err, rs) {
            if (err) {
                console.log(err);
            } else {
                console.log("success.");
            }

        });
    }
    
    res.json({ success: true });}catch(ex){}
});

//新闻管理
//新闻图片
var newsImage = require('../../app_modules/dbAccess/newsImage_Mongo.js');
function savenewsImage(obj) {
    try{
        console.log("newsImage--add");
    var newsImageObj = new newsImage();
    newsImageObj.add({       
        filename: obj.filename,
        createDate: obj.createDate
    }, function (err, rs) {
        if (err) {
            console.log(err);
            console.log("save failed");
            //res.json({ success: false });
        } else {
            //res.json({ success: true });
            console.log("save ok");
        }

    });
}catch(ex){
    console.log(ex.message);
    console.log("save failed");
}
    
}
router.post('/getnewsImages', function (req, res) {
    try{
        console.log("getnewsImages");
    var newsImages = newsImage.find().sort({ createDate: -1 }).exec(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            //console.log("加载完毕：" + (new Date).toLocaleTimeString());
            res.json(result);
        }
    });
}catch(ex){
    res.send("");
}
    
});


router.post('/removenewsImage', function (req, res) {    
    console.log("removenewsImage");
    var id = req.query._id;
    var fileName = req.query.fileName;
    console.log("_id:"+id);
    newsImage.remove({ _id: id }, function (err, rs) {
        try{
            if (err) {           
            res.json({ success: false });
        }
        else {

            fs.unlinkSync("./public/files/upload/" + fileName);
            fs.unlinkSync("./public/files/upload/small/" + fileName);
            res.json({ success: true });
        }
        }
        catch(ex)
        {
            console.log(ex.message);
            res.json({ success: false });
        }
        
    });
});

//news
var companyNew = require('../../app_modules/dbAccess/companyNew_mongo.js');
router.post('/addcompanyNew', function (req, res) {
    try{console.log("addcompanyNew");
    var companyNewObj = new companyNew();
    companyNewObj.add({
        title: req.body.title,
        content: req.body.content,
        order:req.body.order,
        type:req.body.type,
        newImg:req.body.newImg,
		IsUrl:req.body.IsUrl,
		Url:req.body.Url,
        createDate:new Date()
    }, function (err, rs) {
        if (err) {
            console.log(err);
            res.json({ success: false });
        } else {
            res.json({ success: true });
        }

    });    }catch(ex){}
});

router.post('/getnewsList', function (req, res) {
    try{ console.log("getnewsList");
    var pageIndex=req.body.pageIndex-1;
    var pageSize=req.body.pageSize;
    var companyNews = companyNew.find().sort({ createDate: -1 }).skip(pageIndex*pageSize).limit(pageSize).exec(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            res.json(result);
        }
    });}catch(ex){}
});

router.post('/getnewsListByType', function (req, res) {
    try{ console.log("getnewsListByType");
    var pageIndex=req.body.pageIndex-1;
    var pageSize=req.body.pageSize;
    var type=req.body.type;
	var sorter=req.body.sort==undefined?"order":req.body.sort;
	var asc=req.body.asc==undefined?1:req.body.asc;
	var sortFilter={order:asc};
	if(sorter=="createDate"){
		sortFilter={createDate:asc}
	}
	
    var companyNews = companyNew.find({type:type}).sort(sortFilter).skip(pageIndex*pageSize).limit(pageSize).exec(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {
            //console.log("加载完毕：" + (new Date).toLocaleTimeString());
            res.json(result);
        }
    });}catch(ex){}
});

router.post('/removecompanyNew', function (req, res) {    
    console.log("removecompanyNew");
    var id = req.body._id;
    console.log("_id:"+id);
    companyNew.remove({ _id: id }, function (err, rs) {
        try{
            if (err) {           
            res.json({ success: false });
        }
        else {
            res.json({ success: true });
        }
        }
        catch(ex)
        {
            console.log(ex.message);
            res.json({ success: false });
        }
        
    });
});


router.post('/editcompanyNew', function (req, res) {
    try{
       console.log("editcompanyNew");
    var id = req.body._id;
    var tempid = mongoose.Types.ObjectId(id);
    console.log(tempid);
    companyNew.update({ _id: tempid }, {
        $set: {
            title: req.body.title,
            content: req.body.content,
            order:req.body.order,
            type:req.body.type,
            newImg:req.body.newImg,
			IsUrl:req.body.IsUrl,
			Url:req.body.Url,
        }
    }, function (err, rs) {
        if (err) {
            console.log(err);
        } else {
            res.json({ success: true });
        }

    }); 
}catch(ex){
}
    
});


router.post('/getcompanyNew', function (req, res) {
    try{ console.log("getcompanyNew");
    var id=req.body.id;   
    var companyNews = companyNew.findOne({_id:id}).exec(function (err, result) {
        if (err) {
            console.log(err);
            res.send(err);
        } else {           
            res.json(result);
        }
    });}catch(ex){}
});




//login

var adminUserBLL = require('../../app_modules/dbAccess/adminUser_Mongo.js');
var uuid = require('node-uuid');
var moment=require('moment');
router.post('/amdinLogin',function (req, res) {
	console.log("amdinLogin");
	
	var defaltObj={};
	defaltObj.flag=false;	
	
	var usercode=req.body.username;
	var pwd=req.body.password;	
	if(usercode==undefined||pwd==undefined||usercode==""||pwd=="")
	{
		res.json(defaltObj);
		return;
	}
	var r = adminUserBLL.find({usercode:usercode,password:pwd,active:"Y"}, function (err, result) {
        if (!err) {
           var token=uuid.v1();	
           	   
           if(result!=null&&result.length>0){
			   updateToken(result[0]._id,token);
		       defaltObj.flag=true;			   
			   res.cookie('token', token);
               res.cookie('username',result[0].usercode);
		   }		   		   		  
        } 				
		res.json(defaltObj);
    })
});

function updateToken(id,token){
	var time=moment().add(7,"days").format("YYYY-MM-DD HH:MM");
	adminUserBLL.update({_id:id}, {
	$set: {
	token: token,
	expiredDate : time
	}
	}, function (err, rs) {
	});
}

function verifyToken(req, res, next){   
	var token=req.cookies.token;
	console.log(token);
	if(token==undefined||token==""){
	  res.render('admin/login', { title: 'Express' }); 	
	}
	var r = adminUserBLL.find({token:token,active:"Y"}, function (err, result) {
		console.log(result);
        if (!err&&result!=null&&result.length>0) {			
		   if(moment().isBefore(result[0].expiredDate))next();
		   else res.render('admin/login', { title: 'Express' });
		   }
		else{
		res.render('admin/login', { title: 'Express' }); 
		}
    })
}
module.exports = router;
